import 'dart:async';
import 'dart:convert';

import 'package:base_flutter/base_flutter.dart';
import 'package:dart_sm/dart_sm.dart';
import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:ls_work/login/page/user_manager.dart';
import 'package:ls_work/login/user_permission_data.dart';
import 'package:ls_work/res/colors.dart';
import 'package:ls_work/util/ext_utils.dart';
import 'package:ls_work/widgets/common_widget.dart';
import 'package:native_id/native_id.dart';

import '../net/api/http_api.dart';

Future<dynamic> showMobileCheckDialog(
    {required BuildContext context, required String msg, required String mobile,required String account, required String password}) async {
  return await showDialog(context: context, builder: (context) {
    return Dialog(
      child: MobileCheckLoginWidget(msg: msg, mobile: mobile, password: password,account: account,),
    );
  }, barrierDismissible: false);
}

class MobileCheckLoginWidget extends BaseStatefulMvvmWidget {
  String msg;
  String mobile;
  String password;
  String account;

  MobileCheckLoginWidget({required this.msg, required this.mobile, required this.password, required this.account});

  @override
  State<StatefulWidget> createState() => _MobileCheckLoginState();

}


class _MobileCheckLoginState
    extends BaseMvvmState<MobileCheckLoginViewModel, MobileCheckLoginWidget> {
  @override
  Widget? buildLoadingContentView() {
    return Column(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        ...[
          CommonText("新设备登录", fontWeight: FontWeight.bold, textSize: 17)
              .addToContainer(alignment: Alignment.center),
          CommonText(widget.msg, textSize: 14, textColor: Colors.grey),

          CommonText("短信发送至关联号码：${hideMobile(widget.mobile)}", textAlign: TextAlign.center,
              textSize: 14),


          Row(
            children: [
              NoBorderInput(hintText: '输入短信验证码', onChanged: (str) {
                // setState(() {
                viewModel.smsCode = str;
                // });
              }).addToContainer(
                  decoration: BoxDecoration(
                      color: Colours.bg_color,
                      borderRadius: 20.borderRadius
                  ),
                  padding: EdgeInsets.symmetric(horizontal: 10, vertical: 6)
              ).setWeight(1),
              TimeReduceButton(onPressed: () async {
                // viewModel.getVerifyCode();
                return await viewModel.requestSmsCode();
              })
            ],
          ),

          Row(
            children: [
              NoBorderInput(
                  hintText: '输入图形验证码',
                  onChanged: (str) {
                    // setState(() {
                    viewModel.verifyCodeInput = str;
                    // });
                  }
              ).addToContainer(
                  decoration: BoxDecoration(
                      color: Colours.bg_color,
                      borderRadius: 20.borderRadius
                  ),
                  padding: EdgeInsets.symmetric(horizontal: 10, vertical: 6)
              ).setWeight(1),

              // CommonText(viewModel.verifyCode,textSize: 14,fontWeight: FontWeight.bold).setWeight(1),
              if(viewModel.verifyCode.isNullOrEmpty())
                CommonText(
                    "获取验证码", textSize: 14, textColor: Colours.app_main)
              else
                Image.memory(base64Decode(viewModel.verifyCode)).onTap(() {
                  viewModel.getVerifyCode();
                }),

              // if(!viewModel.verifyCodeInput.isNullOrEmpty())

            ],
          ),


          TextButton(onPressed: ()  {
             viewModel.mobileLogin();
          }, child: CommonText('确定',textColor: Colors.white),
          style: TextButton.styleFrom(
            backgroundColor: Colours.app_main,
            shape: StadiumBorder(),
            fixedSize: Size(context.screenSize.width, 44),
          ),)
        ].insertWidget(SizedBox(height: 8,))
      ],
    ).addToContainer(
        padding: EdgeInsets.symmetric(horizontal: 12, vertical: 15)
    );
  }

  @override
  Widget buildRootView(BuildContext context, Widget loadingContentWidget) {
    return loadingContentWidget;
  }

  @override
  MobileCheckLoginViewModel createViewModel() {
    return MobileCheckLoginViewModel(context, mobile: widget.mobile, password: widget.password,account: widget.account);
  }

  @override
  void onRetryClick() {
  }

  String hideMobile(String mobile){
    ///隐藏中间四位
    return mobile.replaceFirst(RegExp(r'\d{4}'), '****', 3);
  }

}


class MobileCheckLoginViewModel extends BaseViewModel {
  String mobile;
  String password;
  String account;

  MobileCheckLoginViewModel(super.context, {required this.mobile, required this.password, required this.account});

  String verifyCode = "";

  String verifyCodeInput = "";

  String smsCode = "";

  ///获取验证码
  Future<void> getVerifyCode() async {
    try {
      var data = await HttpGo.instance.dio!.post(
          "${HttpApi.baseUrl}checkCode/getCheckCode",
          options: Options(
              contentType: Headers.jsonContentType,
              responseType: ResponseType.plain));


      var prik = data!.toString().substring(35, 35 + 64);
      var pck = data.toString().substring(35 + 64, 35 + 64 + 130);

      var imageData = data.toString().substring(0, 35) +
          data.toString().substring(35 + 64 + 130);
      var image = SM2.decrypt(imageData, prik!);

      verifyCode = jsonDecode(image)['data'];
      notifyListeners();

      UserManager.instance.saveItemKey(prik!);
    } catch (e) {
      print("error===>${e}");
      showToast(e.toNetError());
    }
  }

  @override
  void onCreated() {
    super.onCreated();
    getVerifyCode();
  }


  Future<bool> requestSmsCode() async {



    // if (verifyCodeInput.isNullOrEmpty()) {
    //   showToast("请输入图形验证码");
    //   return false;
    // }
    // var code = await showInputVerifyDialog(context);
    // if(code.isNullOrEmpty()){
    //   return false;
    // }
    // if(smsCode.isNullOrEmpty()){
    //   showToast("请输入短信验证码");
    //   return;
    // }
    var url = "${HttpApi.baseUrl}verifyCode/v2/send";
    var map = {
      "mobile": mobile,

      // "code": code,
    };

    try {
      var data = await HttpGo.instance.postData(url,data: map,
          options: Options(contentType: Headers.formUrlEncodedContentType));
      if ("0" == data['code']) {
        showToast("验证码发送成功");
        return true;
      } else {
        showToast(data['msg']);
        return false;
      }
    } catch (e) {
      showToast(e.toNetError());
      return false;
    }
  }

  Future<void> mobileLogin() async {
    if(smsCode.isNullOrEmpty()){
      showToast("请输入短信验证码");
      return;
    }

    var uniCode = await NativeId().getId();
    var params = {
      "username": account,
      "password": password,
      "cryptoType": "sm2",
      "needMenu": true,
      "needAppMenu": true,
      "code": verifyCodeInput,
      "deviceCode": uniCode,
      "smsCode": smsCode,
    };
    showLoadingDialog(msg: '登录中...');
    try {
      var data = await HttpGo.instance.postData(HttpApi.login, data: params,
          options: Options(contentType: Headers.formUrlEncodedContentType));
      hideDialog();
      if ("0" == data['code']) {
        showToast("登录成功");
        Map<String, dynamic> d = data['data'];
        // d["password"] = _pddController.text;
        d['account'] = mobile;
        UserManager.instance.login(d);
        UserPermissionData.saveMenus(d['menus']);
        finish(data: true);
      } else {
        showToast(data['msg']);
        getVerifyCode();
      }
    } catch (e) {

      hideDialog();
      getVerifyCode();
      showToast(e.toNetError());
    }
  }

}

int remainingTime = 60;

Timer? _timer;

class TimeReduceButton extends StatefulWidget {
  Future<bool> Function()? onPressed;

  TimeReduceButton({this.onPressed});

  @override
  State<StatefulWidget> createState() => _TimeReduceButtonState();

}

class _TimeReduceButtonState extends State<TimeReduceButton> {


  String btnText = "获取验证码";


  @override
  Widget build(BuildContext context) {
    return TextButton(
      onPressed: () async {
        if (remainingTime == 60) {
          var success = await widget.onPressed?.call();
          if (success == true) {
            reduceTime();
          }
        }
      },
      child: CommonText(btnText, textSize: 14, textColor: Colours.app_main),
    );
  }


  void reduceTime() {
    if (_timer == null) {
      _timer = Timer.periodic(Duration(seconds: 1), (timer) {
        if (remainingTime == 0) {
          setState(() {
            btnText = "重新获取";
          });
          remainingTime = 60;
          _timer?.cancel();
          _timer = null;
        } else {
          setState(() {
            btnText = "${remainingTime}秒后重新获取";
            remainingTime--;
          });
        }
      });
    }
  }

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((duration) {
      if (_timer != null) {
        _timer?.cancel();
        _timer = null;
        if (remainingTime != 60) {
          reduceTime();
        }
      }
    });
  }
}


Future<String?> showInputVerifyDialog(BuildContext context) async {
  return await showDialog(context: context, builder: (context){
    return Dialog(
      child: InputVerifyCodeWidget(),
    );
  });
}

class InputVerifyCodeWidget extends StatefulWidget{
  @override
  State<StatefulWidget> createState() => _InputVerifyCodeWidgetState();

}

class _InputVerifyCodeWidgetState extends State<InputVerifyCodeWidget>{

  String verifyCode = "";

  String inputCode = "";

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        CommonText('输入验证码'),
        if(verifyCode.isNullOrEmpty())
          CommonText(
              "获取验证码", textSize: 14, textColor: Colours.app_main)
        else
          Image.memory(base64Decode(verifyCode)).onTap(() {
            getVerifyCode();
          }),

        NoBorderInput(hintText: '请输入验证码', onChanged: (v){
          inputCode = v;
        }).addToContainer(
          decoration: BoxDecoration(
            color: Colours.bg_color,
            borderRadius: BorderRadius.circular(8),
          ),
          padding: EdgeInsets.symmetric(horizontal: 12,vertical: 8)
        ),

        TextButton(onPressed: (){
          if(inputCode.isNullOrEmpty()){
            ToastUtils.shotToast("请输入验证码",context: context);
            return;
          }
          Navigator.of(context).pop(inputCode);
        }, child: CommonText('确定',textColor: Colors.white),style: TextButton.styleFrom(
          backgroundColor: Colours.app_main,
          shape: StadiumBorder(),
          fixedSize: Size( 120, 40,)
        ),)
      ].insertWidget(SizedBox(height: 8)),
    ).addToContainer(
      padding: EdgeInsets.symmetric(horizontal: 12,vertical: 12)
    );
  }


  ///获取验证码
  Future<void> getVerifyCode() async {
    try {
      var data = await HttpGo.instance.dio!.post(
          "${HttpApi.baseUrl}checkCode/getCheckCode",
          options: Options(
              contentType: Headers.jsonContentType,
              responseType: ResponseType.plain));


      var prik = data!.toString().substring(35, 35 + 64);
      var pck = data.toString().substring(35 + 64, 35 + 64 + 130);

      var imageData = data.toString().substring(0, 35) +
          data.toString().substring(35 + 64 + 130);
      var image = SM2.decrypt(imageData, prik!);

      setState(() {
        verifyCode = jsonDecode(image)['data'];
      });

      // UserManager.instance.saveItemKey(prik!);
    } catch (e) {
      print("error===>${e}");
    }
  }

  @override
  void initState() {
    super.initState();
    getVerifyCode();
  }
}

